import json
import time
import random
from apis import api_routes
from flask import g, request, jsonify, abort
from security.decoration import certification
from models.logs.logs import Logs
from public.local import date_type
from datetime import datetime, timedelta
from sqlalchemy import and_
from typing import Union
from sqlalchemy import text
from sqlalchemy import distinct
from models.course.course import Course
from models.order.tasks import Tasks
from models.product.routes import Routes
from models.course.detailed import Detailed
from models.facility.facility import Facility
from models.extra.extra import Charge
from models.users.users import Users
from public.config import config
from public.contexts import context_logs


@api_routes.route("/board/configs", methods=["GET"])
@certification(auth=True, role=None)
def func_configs_get_api():
    """
    查询报表岗位负责人姓名， 完成API开发
    http://127.0.0.1:8080/api/board/configs
    Content-Type=application/x-www-form-urlencoded
    methods=["GET"]
    {
    }
    :return:
        {'status': 200, 'data': resp}
    ---
    tags:
      - 看板数据接口设置
    """
    charges: dict = {
        "user1": None,
        "user2": None,
        "user3": None
    }
    charge: Union[Charge, None] = g.session.query(Charge).first()

    if charge is not None:
        parm: dict = {
            1: charge.user_id1,
            2: charge.user_id2,
            3: charge.user_id3
        }
        for index in range(1, 4):
            user: Users = g.session.query(Users).filter(Users.id == parm.get(index)).first()
            user_id: Union[int, None] = user.id if user else None
            user_name: Union[str, None] = user.name if user else None
            charges["user{}".format(index)] = {
                "user_id": user_id,
                "user_name": user_name
            }
    docs: dict = {
        "user1": "现场负责人",
        "user2": "品质负责人",
        "user3": "工艺设备负责人"
    }
    return jsonify({'status': 200, 'data': charges, "docs": docs})


@api_routes.route("/board/configs", methods=["PUT"])
@certification(auth=True, role=None)
def func_configs_put_api():
    """
    修改报表岗位负责人信息， 完成API开发
    全部用户信息查询接口 /api/users/all  GET 获取
    http://127.0.0.1:8080/api/board/configs
    Content-Type=application/json
    methods=["PUT"]
    {
    "user1_id"     int     现场负责人数据库ID
    "user2_id"     int     品质负责人数据库ID
    "user3_id"     int     工艺设备负责人数据库ID
    }
    :return:
        {'status': 4000, 'msg': "根据用户ID查询不到用户"}
        {'status': 200, "msg": "修改成功"}
     ---
    tags:
      - 看板数据接口设置
    """
    data: dict = request.get_json()
    user1: dict = data.get("user1") or {}
    user2: dict = data.get("user2") or {}
    user3: dict = data.get("user3") or {}

    user1_id = user1.get("user_id")
    user2_id = user2.get("user_id")
    user3_id = user3.get("user_id")

    if not all([user1_id, user2_id, user3_id]):
        abort(400)

    array: list = [user1_id, user2_id, user3_id]
    for itr in array:
        user: Users = g.session.query(Users).filter(Users.id == itr).first()
        if user is None:
            return jsonify({'status': 4000, "msg": "根据用户ID查询不到用户"})

    charge: Union[Charge, None] = g.session.query(Charge).first()

    context_logs(name="更新面板负责人", obsolescence=charge.__repr__(), data=json.dumps(data))

    if charge is not None:
        g.session.query(Charge).filter(Charge.id != charge.id).delete()
        g.session.commit()
    charge: Union[Charge, None] = g.session.query(Charge).first()
    if charge is None:
        g.session.add(Charge(
            user_id1=user1_id,
            user_id2=user2_id,
            user_id3=user3_id
        ))
    else:
        charge.user_id1 = user1_id
        charge.user_id2 = user2_id
        charge.user_id3 = user3_id

    g.session.commit()
    return jsonify({'status': 200, "msg": "修改成功"})
